package com.yarolegovich.lovelydialog;

import ohos.utils.PacMap;

import java.lang.ref.WeakReference;
import java.util.HashMap;

/**
 * Created by yarolegovich on 17.04.2016.
 */
public class LovelySaveStateHandler {
    private static final String KEY_DIALOG_ID = "id";
    private HashMap<Integer, WeakReference<AbsLovelyDialog<?>>> handledDialogs;

    public LovelySaveStateHandler() {
        handledDialogs = new HashMap<>();
    }

    public void saveInstanceState(PacMap outState) {
        for (int index = handledDialogs.size() - 1; index >= 0; index--) {
            WeakReference<AbsLovelyDialog<?>> dialogRef = handledDialogs.get(index);
            if (dialogRef.get() == null) {
                handledDialogs.remove(index);
                continue;
            }
            AbsLovelyDialog<?> dialog = dialogRef.get();
            if (dialog.isShowing()) {
                dialog.onSaveInstanceState(outState);
                outState.putIntValue(KEY_DIALOG_ID, index);
                return;
            }
        }
    }

    public void handleDialogStateSave(int id, AbsLovelyDialog<?> dialog) {
        handledDialogs.put(id, new WeakReference<AbsLovelyDialog<?>>(dialog));
    }

    public static boolean wasDialogOnScreen(PacMap savedInstanceState) {
        return savedInstanceState.getKeys().contains(KEY_DIALOG_ID);
    }

    public static int getSavedDialogId(PacMap savedInstanceState) {
        return savedInstanceState.getIntValue(KEY_DIALOG_ID, -1);
    }
}
